import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import com.sun.xml.internal.ws.policy.PolicyConstants;
import javafx.scene.media.SubtitleTrack;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import javax.imageio.ImageReader;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author td
 * @date 2018/5/25
 */
public class main {

    public WebClient getClient(){
      WebClient  webClient = new WebClient();
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        return webClient;
    }

    protected static HtmlUnitDriver login(Map<String, Object> params) {

 /*       ValidateUtils.notEmpty((String) params.get("username"), MessageLocale.EMPTY_CODE, "用户名/手机号不能为空");
        ValidateUtils.notEmpty((String) params.get("password"), MessageLocale.EMPTY_CODE, "密码不能为空");
        //codeKey为用户的session
        ValidateUtils.notEmpty((String) params.get("codeKey"), MessageLocale.EMPTY_CODE, "codeKey不能为空");
        //codeValue为用户的验证码
        ValidateUtils.notEmpty((String) params.get("codeValue"), MessageLocale.EMPTY_CODE, "codeValue不能为空");
    */    //  ValidateUtils.notEmpty();
        WebClient webDriver = new WebClient();
        webDriver.getOptions().setJavaScriptEnabled(true);


    //    client.setWebConnection(httpwebconnection);
        webDriver.getOptions().setUseInsecureSSL(false);
        webDriver.getOptions().setThrowExceptionOnScriptError(false);
        webDriver.getOptions().setThrowExceptionOnFailingStatusCode(false);

        try {

            HtmlPage page = webDriver.getPage("http://www.happyinsurance.com.cn/hlws/product/system/login!toPerUserLogin.action");
            HtmlForm form = page.getForms().get(0);
            HtmlTextInput tetUname = (HtmlTextInput) form.getInputByName("userId");
            tetUname.setValueAttribute((String) params.get("username"));
            System.out.println("用户名:"+tetUname.getText());

            //设置密码
            HtmlPasswordInput tpassword = (HtmlPasswordInput) page.getElementById("userPwd");
            tpassword.setValueAttribute((String) params.get("password"));


            HtmlHiddenInput htmlHiddenInput = (HtmlHiddenInput) page.getElementById("userPwdH");




            HtmlButtonInput buttonInput = form.getInputByName("btnSubmit");

          //
           // System.out.println();

            DomElement domElement = page.getElementById("seccodeimage");

            HtmlImage validateCode = (HtmlImage) domElement.getFirstElementChild();

            ImageReader imageReader = validateCode.getImageReader();
            BufferedImage bufferedImage = imageReader.read(0);
            JFrame f2 = new JFrame();
            JLabel label = new JLabel();
            label.setIcon(new ImageIcon(bufferedImage));
            f2.getContentPane().add(label);
            f2.setSize(100,100);
            f2.setTitle("验证码");
            f2.setVisible(true);
            String valicodeStr = JOptionPane.showInputDialog("请输入验证码：");
            f2.setVisible(false);

            Thread.sleep(5000L);
            System.out.println("验证码为:"+valicodeStr);

            HtmlTextInput yzmInput = form.getInputByName("randomCode");
            yzmInput.setValueAttribute(valicodeStr);
            page.executeJavaScript("userLogin()");
            System.out.println("结果-----"+htmlHiddenInput.getTextContent());


          //  HtmlForm submit = page.getFirstByXPath("//*[@id='submitForm']");
            //提交
            WebResponse response = buttonInput.click().getWebResponse();
            webDriver.waitForBackgroundJavaScript(1000);

            System.out.println(response.getContentAsString());

          //  HtmlPasswordInput tetUname = (HtmlTextInput) form.get("userId");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        // 首先打开页面
      /*  webDriver.get("http://www.happyinsurance.com.cn/hlws/product/system/login!toPerUserLogin.action");

        webDriver.manage().addCookie(new Cookie("JSESSIONID", (String) params.get("codeKey")));
        //把参数提交掉
        //找到账号输入框，输入用户账号
        WebElement userId = webDriver.findElementByName("userId");

        userId.sendKeys((CharSequence) params.get("username"));

        userId.submit();

        System.out.println(userId.getText());*/


  /*      //找到密码输入框
        WebElement password = webDriver.findElementByCssSelector("input#userPwd");

        password.sendKeys((CharSequence) params.get("password"));

        password.submit();
        //找到验证码输入框
        WebElement randomCode = webDriver.findElementByCssSelector("input#randomCode");

        randomCode.sendKeys((CharSequence) params.get("codeValue"));

        randomCode.submit();


        Set<Cookie> cookies = webDriver.manage().getCookies();
        Iterator cookieIt = cookies.iterator();
        while (cookieIt.hasNext()) {
            System.out.println(cookieIt.next());
        }
        //输入完成之后,登录按钮
        WebElement submit = webDriver.findElementByName("btnSubmit");
        System.out.println( "密码"+password.getText());

        submit.click();*/


        //这样就完成了jsession与账号绑定关系了
        return null;


/*
        ResponseEntity<JSONObject> tokenJson = restTemplate.getForEntity(PolicyConstants.HappyInsurance.GET_REPEAT_SUBBMIT_TOKEN, JSONObject.class);
        String repTokenId = "";
        String repTokenValue = "";
        if (tokenJson.getBody().get("repTokenId") != null) {
            repTokenId = (String) tokenJson.getBody().get("repTokenId");
        }
        if (tokenJson.getBody().get("repTokenValue") != null) {
            repTokenValue = (String) tokenJson.getBody().get("repTokenValue");
        }
        HttpHeaders headers = new HttpHeaders();
        //  headers.add("");
        //   restTemplate.exchange()


        return null;*/
    }

    public static void main(String[] args) {

        Map map = new HashMap();

        map.put("username","wokm123");
        map.put("password","wang5689**2698");
        map.put("codeKey","ur6WmXGbUNGQ1LLHnKRQ9UUu--Nuyd1oLCwJFrtf3ZLLMYYv9tJv!-641318244");
        map.put("codeValue","9083");

        HtmlUnitDriver driver = login(map);
   /*     try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(driver.getCurrentUrl());*/



       /* HtmlUnitDriver webDriver = new HtmlUnitDriver(true);
        // 首先打开页面
        webDriver.get("http://www.happyinsurance.com.cn/hlws/product/system/login!toPerUserLogin.action");
        System.out.println(webDriver.getPageSource());*/

       // System.out.println(login(null));

    }
}
